#ifndef __UDP_SEVER_HPP__
#define __UDP_SEVER_HPP__

#include "logmessage.hpp"
#include <string>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class UdpServer
{
    int _sockfd;
    uint16_t _port;
    std::string _ip;

public:
    UdpServer(const std::string &ip, const uint16_t port)
        : _ip(ip),
          _port(port),
          _sockfd(-1)
    {
    }

    void InitServer()
    {
        // 1.创建套接字文件描述符
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            LogMessage(FATAL, "(%d)%s", errno, strerror(errno));
            exit(errno);
        }

        // 2.手动绑定文件描述符和套接字结构
        // 将用户设置的ip和port在内核中和当前进程强关联
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int ret = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (ret == -1)
        {
            LogMessage(FATAL, "(%d)%s", errno, strerror(errno));
            exit(errno);
        }

        LogMessage(DEBUG, "init server success!");
    }

    void Start()
    {
        char buffer[1024];
        for (;;)
        {
            sockaddr_in client;             // 输出型参数
            socklen_t len = sizeof(client); // 输入输出型参数：输入：client缓冲器的大小，输出：实际读到的client的大小
            memset(&client, 0, sizeof(client));

            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&client, &len);
            if (s == -1)
            {
                LogMessage(ERROR, "(%d)%s", errno, strerror(errno));
                continue;
            }

            if (s > 0)
            {
                buffer[s] = 0;
                std::string client_ip = inet_ntoa(client.sin_addr); // 注意inet_ntoa的参数是sin_addr结构
                uint16_t client_port = ntohs(client.sin_port);
                printf("[%s:%d]# %s\n", client_ip.c_str(), client_port, buffer);
            }
        }
    }

    ~UdpServer()
    {
        if (_sockfd >= 0)
            close(_sockfd);
    }
};

#endif